package tw.com.msig.b2c.car.security.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SecurityFilter implements Filter {

	private Logger log = LoggerFactory.getLogger(SecurityFilter.class);
	
	@Override
	public void init(FilterConfig fc) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		HttpSession session = req.getSession();
		
		if(session.getAttribute("b2cUser") == null) {
			log.debug("{}", req.getRequestURI().indexOf("login"));
			
			if(	req.getRequestURI().indexOf("login.jsp") < 0 
				&& req.getRequestURI().indexOf("auth.do") < 0 
				&& req.getRequestURI().indexOf("/resources/") < 0
				&& req.getRequestURI().indexOf("/services/") < 0) {
				
				res.sendRedirect(req.getContextPath()+"/login.jsp");
			
			}
		}
		
		chain.doFilter(request, response);
		
		
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
